package cn.xinagxu.cglib_proxy;

import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

import javax.xml.ws.Service;
import java.lang.reflect.Method;

/**
 * @author 王杨帅
 * @create 2018-08-19 21:03
 * @desc
 **/
public class CglibFactory implements MethodInterceptor {

    private SomeService target;

    public CglibFactory(SomeService someService) {
        this.target = someService;
    }

    public CglibFactory() {
    }

    // 创建代理对象的方法
    public SomeService createProxy() {

        // 01 创建一个增强器
        Enhancer enhancer = new Enhancer();

        // 02 设置增强方
        enhancer.setSuperclass(target.getClass());

        // 03 接口回调方法
        enhancer.setCallback(this);

        // 04 返回代理对象
        return (SomeService) enhancer.create();

    }

    // 跟JDK动态代理的invoke方法差不多
    public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {

        if ("someMethod01".equals(method.getName())) {
            String str = (String) method.invoke(target, objects);
            return str.toUpperCase();
        } else {
            Object result = method.invoke(target, objects);
            return result;
        }

    }

}
